import {
	TUIChatService,
	TUIStore,
	StoreName,
	TUITranslateService,
	IConversationModel,
	SendMessageParams,
} from "@tencentcloud/chat-uikit-engine";
import { Toast, TOAST_TYPE } from "../../common/Toast/index";
import { isEnabledMessageReadReceiptGlobal } from "../utils/utils";
import { ITipTapEditorContent } from "../../../interface";
import { enableSampleTaskStatus } from "../../../utils/enableSampleTaskStatus";

import { HTTP_REQUEST_URL, PERFIX } from '@/config/app.js';

export const sendMessageErrorCodeMap : Map<number, string> = new Map([
	[3123, "文本包含本地审核拦截词"],
	[4004, "图片消息失败,无效的图片格式"],
	[4005, "文件消息失败,禁止发送违规封禁的文件"],
	[7004, "文件不存在,请检查文件路径是否正确"],
	[7005, "文件大小超出了限制,如果上传文件,最大限制是100MB"],
	[8001, "消息长度超出限制,消息长度不要超过12K"],
	[80001, "消息或者资料中文本存在敏感内容,发送失败"],
	[80004, "消息中图片存在敏感内容,发送失败"],
]);

/**
 * 该函数仅处理 Text TextAt Image Video File 五种消息类型
 * @param messageList
 * @param currentConversation
 */
export const sendMessages = async (
	messageList : ITipTapEditorContent[],
	currentConversation : IConversationModel
) => {
	// 有 messageJumping 的情况下，发送消息自动清空，回到底部
	if (TUIStore.getData(StoreName.CHAT, "messageSource")) {
		TUIStore.update(StoreName.CHAT, "messageSource", undefined);
	}
	messageList?.forEach(async (content : ITipTapEditorContent) => {
		try {
			const options : SendMessageParams = {
				to: currentConversation?.groupProfile?.groupID || currentConversation?.userProfile?.userID,
				conversationType: currentConversation?.type as any,
				payload: {},
				needReadReceipt: isEnabledMessageReadReceiptGlobal(),
			};
			
			const from_userId = uni.getStorageSync('mobile')
			const to_userId = currentConversation?.userProfile?.userID
			const nickname = uni.getStorageSync('nickname');
			
			// handle message typing
			switch (content?.type) {
				
				case "text":
					const textMessageContent = JSON.parse(JSON.stringify(content?.payload?.text));
					// 禁止发送空消息
					if (!textMessageContent) {
						break;
					}
					
					console.log('发消息')
					
					
					if (content?.payload?.atUserList) {
						let oldText = JSON.parse(JSON.stringify(content?.payload?.text))
						let tranText = await textTranslation(oldText, from_userId, to_userId)
						
						if(getApp().globalData.site.im_limit==1){
							if(isValidLength(tranText)){
								tranText = getApp().globalData.site.im_limit_text
							}
							
							var im_limit_content = getApp().globalData.site.im_limit_content
							console.log(im_limit_content)
							for(var i=0;i<im_limit_content.length;i++){
								if (tranText.indexOf(im_limit_content[i]) !== -1) {
									tranText = getApp().globalData.site.im_limit_text
									break;
								}
							}
						}
						
						options.payload = {
							text: tranText,
							atUserList: content?.payload?.atUserList,
						};
						await TUIChatService?.sendTextAtMessage(options,{offlinePushInfo: {title: nickname,description: tranText, extension: tranText}});
						pushAction(from_userId,to_userId,tranText);
					} else {
						let oldText = JSON.parse(JSON.stringify(content?.payload?.text))
						let tranText = await textTranslation(oldText, from_userId, to_userId)
						
						if(getApp().globalData.site.im_limit==1){
							if(isValidLength(tranText)){
								tranText = getApp().globalData.site.im_limit_text
							}
							
							var im_limit_content = getApp().globalData.site.im_limit_content
							console.log(im_limit_content)
							for(var i=0;i<im_limit_content.length;i++){
								if (tranText.indexOf(im_limit_content[i]) !== -1) {
									tranText = getApp().globalData.site.im_limit_text
									break;
								}
							}
						}
						
						options.payload = {
							text: tranText,
						};
						
						
						await TUIChatService?.sendTextMessage(options,{offlinePushInfo: {title: nickname,description: tranText, extension: tranText}});
						pushAction(from_userId,to_userId,tranText);
					}
					break;
				case "image":
					options.payload = {
						file: content?.payload?.file,
					};
					await TUIChatService?.sendImageMessage(options);
					//pushAction(from_userId,to_userId,"image");
					break;
				case "video":
					options.payload = {
						file: content?.payload?.file,
					};
					await TUIChatService?.sendVideoMessage(options);
					//pushAction(from_userId,to_userId,"video");
					break;
				case "file":
					options.payload = {
						file: content?.payload?.file,
					};
					await TUIChatService?.sendFileMessage(options);
					//pushAction(from_userId,to_userId,"file");
					break;
				default:
					break;
			}
			
			enableSampleTaskStatus("sendMessage");
	
		} catch (error : any) {
			Toast({
				message: sendMessageErrorCodeMap.get(error?.code)
					? TUITranslateService.t(`TUIChat.${sendMessageErrorCodeMap.get(error.code) as string}`)
					: error?.message,
				type: TOAST_TYPE.ERROR,
			});
			// 如果消息发送失败，且该消息为引用消息，清除引用消息信息
			if (TUIStore.getData(StoreName.CHAT, "quoteMessage")) {
				TUIStore.update(StoreName.CHAT, "quoteMessage", {});
			}
		}
	});
};

export const pushAction = (from_userId:any,to_userId:any,text:any) =>{
	uni.request({
		url: HTTP_REQUEST_URL + '/users/push/send',
		data: {
			from_mobile: from_userId,
			to_mobile: to_userId,
			text: text,
			lang: getApp().globalData.lang
		},
		method:'POST',
		header: {},
		success: (res) => {
			console.log({
			from_mobile: from_userId,
			to_mobile: to_userId,
			text: text,
			lang: getApp().globalData.lang
		})
			console.log(res)
		}
	})
};


export const isValidLength= (number : any) => {
    //return /^\D*(\d{11}|\d{10})\D*$/.test(number);
	return /\d{5}/g.test(number);
};




export const handleMessageWithTyping = (cloudCustomData : any) => {
	if (!cloudCustomData) {
		cloudCustomData = {};
	}
	cloudCustomData.messageFeature = {
		needTyping: 1,
		version: 1,
	};
	return cloudCustomData;
};

export const sendTyping = (inputContentEmpty : boolean, inputBlur : boolean) => {
	if (!inputContentEmpty && !inputBlur) {
		TUIChatService.enterTypingState();
	} else {
		TUIChatService.leaveTypingState();
	}
};

const textTranslation = async (text : any, from_userId : any, to_userId : any) => {
	// TODO::根据双方国籍，判断是否需要翻译
	console.log('新增翻译 = from---to---text', from_userId + '---' + to_userId + '---' + text)
	return new Promise((resolve, reject) => {
		
		var tranText = text;
		if(getApp().globalData.site.im_limit==1){
			if(isValidLength(tranText)){
				tranText = getApp().globalData.site.im_limit_text
			}
			
			var im_limit_content = getApp().globalData.site.im_limit_content
			for(var i=0;i<im_limit_content.length;i++){
				if (tranText.indexOf(im_limit_content[i]) !== -1) {
					tranText = getApp().globalData.site.im_limit_text
					break;
				}
			}
		}
		text = tranText;
		
		uni.request({
			url: HTTP_REQUEST_URL + '/common/textTranslate',
			data: {
				from_mobile: from_userId,
				to_mobile: to_userId,
				text: text
			},
			header: {},
			success: (res) => {
				if (res.data.code !== 1) {
					resolve(text)
				}
				// let tranText = text + '（' + res.data.data.TargetText + '）'
				let tranText = res.data.data
				console.log('textTranslation-res', tranText)
				resolve(tranText)
			},
			fail: (err) => {
				reject(text)
			}
		})
	});
};